# coding=utf-8
# 把目录列表转为xml结构

import re
from xml.dom import minidom

p = r'D:\1.txt'  # 输入
s = open(p).read()

s = re.sub(r'[\r\n]第\s*?(\d+)\s*?章\s', r'\n\1 ', s)
s = re.sub(r'[\r\n](?=\d)', r'\n0.', s)
s = re.sub(r'(?:[\r\n]|^)第\s*?(\d+)\s*?篇\s', r'\n\1 ', s)

print s
l = re.findall(r'(?<=\n)\d+(?:\.\d+)*.+(?=\n)', s)

for i in l: s = s.replace(i, '')
s = re.sub(r'([\r\n])+\s*\1+', r'\1', s)


ll = []

for i in l:
    a = re.match(r'(\d+(?:\.\d+)*)\s*(.+?)\s*(\d+)\s*$', i)
    ll += [(a.group(1), a.group(2), a.group(3))]

doc = minidom.Document()
root = doc.createElement('文档书签')

seq = [root] + [1] * 5
for i in ll:
    j = i[0].count('.') + 1
    seq[j] = doc.createElement('书签')
    seq[j].setAttribute('页码', i[2])
    seq[j].setAttribute('动作', '转到页面')
    seq[j - 1].appendChild(seq[j])

    if j == 1:
        seq[j].setAttribute('默认打开', '是')
        seq[j].setAttribute('文本', '第' + i[0] + '篇 ' + i[1])
    else:
        seq[j].setAttribute('文本', i[0][2:] + ' ' + i[1])

pdfInfo = doc.createElement('PDF信息')
pdfInfo.appendChild(root)
doc.appendChild(pdfInfo)

s = doc.toprettyxml()

s = s.replace('?>', 'encoding="gb2312"?>', 1)

print s

p = p[:-3] + 'xml'  # 输出

open(p, 'w').write(s.decode('utf-8').encode('gb2312'))
